import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/Login',
        name: 'Login',
        component: Login
    },
    {
        path: '/Home',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true }
    },

]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 添加全局前置守卫
router.beforeEach(async (to, from, next) => {
    console.log('路由守卫触发, 目标路由:', to.path)

    // 获取存储的用户ID
    const userId = localStorage.getItem('userId')
    console.log('当前存储的 userId:', userId)

    // 如果是首次加载应用
    if (from.path === '/') {
        console.log('首次加载应用，清除所有存储')
        localStorage.clear()
        next('/login')
        return
    }

    // 处理需要认证的路由
    if (to.meta.requiresAuth) {
        if (!userId) {
            console.log('需要认证但未登录，重定向到登录页')
            next('/login')
            return
        }
    }

    // 已登录用户访问登录页
    if (to.path === '/login' && userId) {
        console.log('已登录用户访问登录页，重定向到首页')
        next('/home')
        return
    }

    next()
})

export default router
